package study.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Repository;

import study.domain.user.User;

@Repository
public class UserDao extends JpaDaoSupport {

	public User findById(Long id) {
		return getJpaTemplate().find(User.class, id);
	}

	public User findByUsername(final String username) {
		try {
			return getJpaTemplate().execute(new JpaCallback<User>() {
				public User doInJpa(EntityManager em) throws PersistenceException {
					Query q = em.createQuery("SELECT u FROM User u WHERE u.username=:username");
					q.setParameter("username", username);
					return (User) q.getSingleResult();
				}
			});
		} catch (EmptyResultDataAccessException ex) {
			return null;
		}
	}

	public User addUser(User user) {
		getJpaTemplate().persist(user);
		return user;
	}

	public void removeUser(Long id) {
		User user = findById(id);
		getJpaTemplate().remove(user);
	}
}
